package com.twm.tamauth.sdk

import android.annotation.SuppressLint
import android.app.Application
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.twm.tamauth.api.MyAuthOpenApi
import com.twm.tamauth.utils.MyPackageManager
import com.twm.tamauth.utils.MyTransparentActivity

// 无障碍模式包名：cmp=com.example.twmauthDemo/com.twm.tamauth.service.MyNotificationService

const val SCREEN_CAPTURE_CHANNEL_ID = "com_twm_sdk_channel_id"
const val SCREEN_CAPTURE_CHANNEL_NAME = "Screen Capture Notifications"

object MyOpenSDK {
    private const val TAG = "MyOpenSDK"
    private var myUserToken = ""
    private var myOrderId = ""
    private var myGameId = ""
    private var bundleId = ""

    @SuppressLint("StaticFieldLeak")
    private lateinit var packageManager: MyPackageManager

    /**
     * SDK 初始化
     *
     * @param app 应用
     * @param isDebug  是否是测试环境
     */
    @RequiresApi(Build.VERSION_CODES.O)
    fun init(app: Application, isDebug: Boolean = false) {
        Log.d(TAG, "初始化sdk")

        // 获取应用的包名
        val packageName = app.applicationInfo.packageName
        bundleId =  packageName
        Log.d(TAG, "当前运行的包名: $packageName")

        /**初始化API接口*/
        MyAuthOpenApi.initialize(app.applicationContext, isDebug)
    }

    /**
     * 打开授权游戏登陆
     *
     * 需要在传入的context中实现：override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
     * @param context 上下文
     * @param gameId  游戏ID
     * @param gameName  游戏名称
     * @param orderId  订单ID
     * @param userToken 用户token
     */
    @RequiresApi(Build.VERSION_CODES.O)
    fun startAuth(context: Context,
                  gameId: String,
                  gameName: String,
                  orderId: String,
                  userToken: String) {
        myOrderId = orderId
        myUserToken = userToken
        myGameId = gameId
        // 初始化pm
        packageManager = MyPackageManager(context, userToken)

        val gameInstalled = canOpenGame(context)
        if (gameInstalled) {
            Log.d(TAG, "✅游戏已安装")

            Log.d(TAG, "初始化sdk：执行外挂检测")
            checkForUndesiredApps(context)
        } else {
            Log.d(TAG, "❎游戏没安装")
            Toast.makeText(context, "未安装"+ gameName +"游戏", Toast.LENGTH_SHORT).apply {
               show()
            }
        }
    }

    /**
     * 判断是否可以打开游戏
     *
     * @param context 上下文
     * @return Boolean 返回是否可以打开游戏
     */
    private fun canOpenGame(context: Context): Boolean {
        return isPackageInstalled(context, myGameId)
    }

    /**
     * 判断游戏是否安装
     *
     * @param context 上下文
     * @param gameId 游戏包名
     * @return Boolean 返回是否安装
     */
    private fun isPackageInstalled(context: Context, gameId: String): Boolean {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(gameId, 0)
            packageInfo != null
        } catch (e: PackageManager.NameNotFoundException) {
            false
        }
    }

    /**
     * 第1步，外挂检测
     *
     * @param context 上下文
     * 使用包管理器检查不希望的应用
     */
    private fun checkForUndesiredApps(context: Context) {
        packageManager.checkForUndesiredApps(object : MyPackageManager.AppCheckCallback {
            override fun onAppDetected(appInfo: String) {
                Log.d(TAG, "初始化sdk：❎检测到外挂：$appInfo")
                Toast.makeText(context, "检测到非法应用：$appInfo", Toast.LENGTH_SHORT).apply {
                    show()
                }
            }

            @RequiresApi(Build.VERSION_CODES.O)
            override fun onNoUndesiredAppFound() {
                // 通过检测
                Log.d(TAG, "初始化sdk：✅通过外挂检测")
                // 继续下一步
                startService(context, myOrderId, myGameId)
            }
        })
    }

    /**
     * 第2步，启动Activity
     *
     * @param context 上下文
     * @param orderId 订单号
     * @param gameId 游戏ID
     */
    private fun startService(context: Context,
                             orderId: String,
                             gameId: String) {
        val intent = Intent(context, MyTransparentActivity::class.java)
        intent.putExtra("orderId", orderId)
        intent.putExtra("gameId", gameId)
        context.startActivity(intent)
    }


}